package com.aidex.business.controller.login;

import com.aidex.business.service.apiService.intfc.IIasApiService;
import com.aidex.common.constant.Constants;
import com.aidex.common.core.domain.AjaxResult;
import com.aidex.common.exception.BizException;
import com.aidex.framework.manager.AsyncManager;
import com.aidex.framework.manager.factory.AsyncFactory;
import com.aidex.framework.web.service.SysLoginService;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/business/ca")
public class CaLoginController {

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private IIasApiService iasApiService;

    /**
     * 登录方法
     *
     * @param params 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map<String, String> params) {
        AjaxResult ajax = AjaxResult.success();
        String rspStr = iasApiService.verifyboundvalue(params);
        JSONObject obj = JSONObject.parseObject(rspStr);
        Integer statusCode = obj.getInteger("statusCode");
        if (statusCode != 0) {
            String eventMsg = obj.getString("eventMsg");
            String errMsg = String.format("医院统一认证服务响应异常, %s", eventMsg);
            AsyncManager.me()
                .execute(AsyncFactory.recordLogininfor("", Constants.LOGIN_FAIL, errMsg));
            throw new BizException(errMsg);
        }
        JSONObject eventValue = obj.getJSONObject("eventValue");
        if (null == eventValue) {
            String errMsg = "医院统一认证服务响应异常, eventValue字段为空";
            AsyncManager.me()
                .execute(AsyncFactory.recordLogininfor("", Constants.LOGIN_FAIL, errMsg));
            throw new BizException(errMsg);
        }

        String relBizNo = obj.getJSONObject("eventValue").getString("relBizNo");
        String checkKey = obj.getJSONObject("eventValue").getString("checkKey");
        String encryptedToken = obj.getJSONObject("eventValue").getString("encryptedToken");

        // 生成令牌
        String token = loginService.login(relBizNo, checkKey);
        ajax.put(Constants.TOKEN, token);
        ajax.put("encryptedToken", encryptedToken);
        return ajax;
    }

}
